# coding=utf-8
from urllib.parse import urljoin
import requests
from lxml import html
from PIL import Image
import re
import os
import mysqlClass

# home_page = http://59.69.173.117/jwweb       method=GET    # 教务网主页
# login_url = http://59.69.173.117/jwweb/_data/index_LOGIN.aspx，   method=POST    # 教务网post登陆地址
# Vcode_url = http://59.69.173.117/jwweb/sys/ValidateCode.aspx，   method=GET   # 获取验证码验证码地址
# Basic_info_url = http://59.69.173.117/jwweb/xsxj/Stu_MyInfo_RPT.aspx,  method=GET  # 基本信息获取地址,从中提取照片id
# your_image = http://59.69.173.117/jwweb/_photo/student/20150000331008.JPG,  method=GET  # 顾名思义
# score_url = http://59.69.173.117/jwweb/xscj/Stu_MyScore_rpt.aspx method=POST 有两次请求GET,POST
# ASP.NET_SessionId: skiqda2icigeeyv4phnuqk55  cookie格式

# 下面的类主要构建Header请求头和post数据以及加密密码于验证码,即时模拟登录
class Login:
    # Basic_info是个字典{"user_id":"20140123","pwd":"146012"}
    def __init__(self,Basic_info):
        self.user_id = Basic_info["user_id"]
        self.pwd = Basic_info["pwd"]
        self.vcode = Basic_info["vcode"]
        self.home_url = "http://59.69.173.117/jwweb/"
        self.login_url = urljoin(self.home_url, '_data/index_LOGIN.aspx')
        self.vcode_url = urljoin(self.home_url, 'sys/ValidateCode.aspx')
        self.image_url = urljoin(self.home_url, 'xsxj/Stu_MyInfo_RPT.aspx')
        self.score_url = urljoin(self.home_url, 'xscj/Stu_MyScore_rpt.aspx')
        self.session_id = requests.session()

    def Header(self, url):
        Basic_Header = {

            "Accept": "image / gif,image / jpeg, image / pjpeg, application / x - ms - application, application / xaml + xml, application / x - ms - xbap, * / *",
            "Accept - Encoding": "gzip, deflate",
            "Accept - Language": "zh - Hans - CN, zh - Hans; q = 0.5",
            "Cache-Control": "max-age=0",
            "Connection": "Keep - Alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)",
        }
        if url == "home":
            Basic_Header["Referer"] = self.home_url
            return Basic_info
        elif url == "login":
            Basic_Header["Referer"] = self.login_url
            return Basic_info
        elif url == "image":
            Basic_Header["Referer"] = self.image_url
            return Basic_info
        elif url == "score":
            Basic_Header["Referer"] = self.score_url
            return Basic_info

    def Post_data(self):
        post_data = {
            "Sel_Type": "STU",
            "typeName": "学生".encode('gb2312'),

            "UserID": "",  # 学号
            "PassWord": "",  # 密码
            "cCode": "",    # 验证码

            "pcInfo": "Mozilla%2F4.0+%28compatible%3B+MSIE+7.0%3B+Windows+NT+10.0%3B+WOW64%3B+Trident%2F7.0%3B+.NET4.0C%3B+.NET4.0E%3B+.NET+CLR+2.0.50727%3B+.NET+CLR+3.0.30729%3B+.NET+CLR+3.5.30729%29x860+SN%3ANULL",

        }
        # re = self.session_id.get(url=self.home_url, headers=self.Header(url="home"))
        response = self.session_id.get(url=self.login_url, headers=self.Header(url="login"))
        if response.status_code == 200:
            selector = html.fromstring(response.text)
            post_data["__VIEWSTATE"] = selector.xpath("//*[@id='Logon']/input[1]/@value")[0]
            post_data["__VIEWSTATEGENERATOR"] = selector.xpath("//*[@id='Logon']/input[2]/@value")[0]
            post_data["UserID"] = self.user_id
            post_data["PassWord"] = self.pwd
            post_data["cCode"] = self.Get_vcode()

            return post_data
        else:
            print("错误响应的不是200")

    def Get_vcode(self):
        self.session_id.get(url=self.login_url, headers=self.Header(url="login"))
        response = self.session_id.get(url=self.vcode_url, headers=self.Header(url="login"))
        # print(response)
        with open('vcode.gif', 'wb') as f:
            f.write(response.content)
        f.close()
        # 显示验证码
        img = Image.open('vcode.gif')
        img.show()
        code = input("请输入验证码:")
        return code

    def Get_imgid(self):
        response = self.session_id.get(url=self.image_url, headers=self.Header(url="image"))
        img_id = re.findall(r"[/](\d+).\w+", response.text)
        # /img_id.JPG
        # 201400000239
        return img_id[0]

    def Post_data_score(self):
        img_id = self.Get_imgid()
        print(img_id)
        # 检索入学以来所有成绩
        post_data_score = {
            "btn_search": "检索".encode('gb2312'),
            "SelXNXQ": "0",  # 学年,学期 0->入学以来,1->学年,2->学期
            "SJ": "1",  # 1
            "txt_xm": img_id,  # 目测是图片编号
            "zfx_flag": "0",  #
        }
        # 目测是漏洞,只要登录一次post的txt_xm不同就能得到不同的数据
        # 若有需要可以更改POST值检索不同年份的值
        return post_data_score

    def Get_score(self):
        response = self.session_id.post(url=self.score_url,data=self.Post_data_score(), headers=self.Header(url="score"))
        filename = 'score/' + self.user_id + '.html'
        with open(filename, 'wb') as f:
            f.write(response.content)
        f.close()

    def Try_login(self):
        response = self.session_id.post(url=self.login_url,data=self.Post_data(), headers=self.Header(url="login"))
        if re.search("正在加载权限", response.text):
            print("登录成功!")
            self.Get_score()
        elif re.search("账号或密码不正确", response.text):
            print("账号或密码不正确!")
        elif re.search("验证码错误", response.text):
            print("验证码错误!")
        else:
            print("登录失败!")


if __name__ == '__main__':
    user = input("请输入学号:")
    pwd = input("请输入密码:")

    Basic_info = {
        "user_id": user,
        "pwd": pwd,
        "vcode": ""
    }
    login = Login(Basic_info)
    login.Try_login()
